package com.example.cursor_service.impl;

import com.example.cursor_service.UserLogService;
import com.example.cursor_orm.model.UserLog;
import com.example.cursor_orm.dao.UserLogDAO;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.ArrayList;

@Service
public class UserLogServiceImpl implements UserLogService {
    private final UserLogDAO logDAO;
    
    public UserLogServiceImpl(UserLogDAO logDAO) {
        this.logDAO = logDAO;
    }
    
    @Override
    public UserLog createLog(UserLog log) {
        try {
            logDAO.insert(log);
            return log;
        } catch (Exception e) {
            return null;
        }
    }
    
    @Override
    public UserLog getLogById(Integer id) {
        try {
            return logDAO.findById(id);
        } catch (Exception e) {
            return null;
        }
    }
    
    @Override
    public boolean deleteLog(Integer id) {
        try {
            return logDAO.deleteById(id) > 0;
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public List<UserLog> getLogList(int page, int size) {
        try {
            List<UserLog> all = logDAO.findAll();
            int from = Math.max(0, (page - 1) * size);
            int to = Math.min(all.size(), from + size);
            return all.subList(from, to);
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
    
    @Override
    public List<UserLog> getLogsByUserId(Integer userId) {
        try {
            return logDAO.findByUserId(userId);
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
    
    @Override
    public List<UserLog> getLogsByAction(String action) {
        try {
            return logDAO.findByAction(action);
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
    
    @Override
    public List<UserLog> getLogsByTimeRange(LocalDateTime start, LocalDateTime end) {
        try {
            return logDAO.findByTimeRange(start, end);
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
    
    @Override
    public int deleteLogsBefore(LocalDateTime beforeTime) {
        try {
            return logDAO.deleteLogsBefore(beforeTime);
        } catch (Exception e) {
            return 0;
        }
    }
} 